package edu.ccut.saturn.studio.dialog.workflowdialog;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import edu.ccut.saturn.studio.Activator;
import edu.ccut.saturn.studio.Images;
import edu.ccut.saturn.studio.core.search.SaturnFileSearcher.SearchResult;
import edu.ccut.saturn.studio.core.search.dialog.OneCompontentSearchDialog;
import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.core.util.xml.SaturnW3CUtil;
import edu.ccut.saturn.studio.dialog.MyCellModifierParameterFromWorkflow;
import edu.ccut.saturn.studio.dialog.SelectionCandidate;
import edu.ccut.saturn.studio.dialog.TableViewerContentProvider;
import edu.ccut.saturn.studio.dialog.TableViewerLableProvider;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnParameter;
import edu.ccut.saturn.studio.logic.model.saturn.SaturnWorkflowNodeInLogic;
import edu.ccut.saturn.studio.util.ConversionUtil;

public class SaturnWorkflowDialogInLogic extends TitleAreaDialog {

	private Text idText;
	protected TableViewer tableViewer;

	private Table table;

	private Text nameText, expressionText, versionText, descriptionText,
			creatorText;

	private Label nameLabel, expressionLabel, versionLabel, descriptionLabel,
			creatorLabel, transactionTypeLabel, browser;

	private Combo transactionTypeCombo;

	// 初始化模型的parameterList
	private List<SaturnParameter> parameterlist = new ArrayList<SaturnParameter>();

	// 初始化表格里显示的parameterList（去除模型的paramterList的最后一条）
	private List<SaturnParameter> tableVisualListTemp = new ArrayList<SaturnParameter>();

	private Shell shell;

	private SaturnWorkflowNodeInLogic saturnWorkflowNodeInLogic;


	private boolean serach = false;

	public SaturnWorkflowDialogInLogic(Shell parentShell,
			SaturnWorkflowNodeInLogic saturnWorkflowNodeInLogic) {
		super(parentShell);
		this.shell = parentShell;
		this.saturnWorkflowNodeInLogic = saturnWorkflowNodeInLogic;
		this.setParameterList(saturnWorkflowNodeInLogic.getParameters());// 得到两个parameterList
	}

	protected Control createContents(Composite parent) {
		Control contents = super.createContents(parent);
		setMessage(SelectionCandidate.SETTING_ATTRIBUTE
				+ saturnWorkflowNodeInLogic.getName());
		return contents;
	}

	@Override
	protected Control createDialogArea(Composite parent) {

		getShell().setText(SelectionCandidate.ATTRIBUTE_SETTING);
		setTitleImage(Activator.getImage(Images.SATURN_ICONS_MAXNAME));

		Composite area = (Composite) super.createDialogArea(parent);
		Composite container = new Composite(area, SWT.NONE);

		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 3;
		container.setLayout(gridLayout);
		container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

		final Label idLabel = new Label(container, SWT.NONE);
		final GridData gd_idLabel = new GridData();
		gd_idLabel.verticalIndent = 10;
		idLabel.setLayoutData(gd_idLabel);
		idLabel.setText("ID");

		idText = new Text(container, SWT.READ_ONLY | SWT.BORDER);
		final GridData gd_idText = new GridData(SWT.FILL, SWT.FILL, true, false,2,1);
		idText.setLayoutData(gd_idText);
		gd_idText.verticalIndent = 10;
		gd_idText.horizontalIndent = 10;
		gd_idText.widthHint = 621;

		nameLabel = new Label(container, SWT.NONE);
		final GridData gd_nameLabel = new GridData();
		gd_nameLabel.verticalIndent = 10;
		nameLabel.setLayoutData(gd_nameLabel);
		nameLabel.setText(Messages.getString("SaturnWorkflowDialogInLogic.name")); //$NON-NLS-1$

		nameText = new Text(container, SWT.BORDER | SWT.READ_ONLY);
		final GridData gd_nameText = new GridData(SWT.FILL, SWT.FILL, true,
				false, 2, 1);
		gd_nameText.verticalIndent = 10;
		gd_nameText.horizontalIndent = 10;
		gd_nameText.widthHint = 621;
		nameText.setLayoutData(gd_nameText);

		expressionLabel = new Label(container, SWT.NONE);
		final GridData gd_expressionLabel = new GridData();
		gd_expressionLabel.verticalIndent = 10;
		expressionLabel.setLayoutData(gd_expressionLabel);
		expressionLabel.setText(Messages
				.getString("SaturnWorkflowDialogInLogic.expression")); //$NON-NLS-1$

		expressionText = new Text(container, SWT.BORDER | SWT.READ_ONLY);
		final GridData gd_expressionText = new GridData(SWT.FILL, SWT.CENTER,
				true, false);
		gd_expressionText.verticalIndent = 10;
		gd_expressionText.horizontalIndent = 10;
		expressionText.setLayoutData(gd_expressionText);

		browser = new Label(container, SWT.NONE);
		browser.setImage(Activator.getImage(Images.AMPLIFY_PLUS));
		final GridData gd_browser = new GridData();
		gd_browser.verticalIndent = 10;
		browser.setLayoutData(gd_browser);
		browser.addMouseTrackListener(new MouseTrackAdapter() {
			public void mouseEnter(final MouseEvent e) {
				browser
						.setImage(Activator.getImage(Images.AMPLIFY_MINUS));
			}

			public void mouseExit(final MouseEvent e) {
				browser.setImage(Activator.getImage(Images.AMPLIFY_PLUS));
			}
		});
		browser.addMouseListener(new MouseAdapter() {
			public void mouseDown(final MouseEvent e) {
//				IRunnableWithProgress op = new IRunnableWithProgress() {
//					public void run(IProgressMonitor monitor)
//							throws InvocationTargetException {
//						monitor.beginTask("Search...", 100);
//						GUIUpdater g = new GUIUpdater(monitor);
//						Thread t = new Thread(g);
//						t.start();
//
//						tempMap = saturnWorkflowNodeInLogic.keyMapInProject();
//					}
//				};
//				try {
//					new ProgressMonitorDialog(getShell()).run(true, false, op);
//				} catch (Exception e1) {
//				}
//
//				serach = true;
//				if (tempMap == null) {
//					return;
//				}
//
//				CustomerFilterDialog dialog1 = new CustomerFilterDialog(shell,
//						saturnWorkflowNodeInLogic);
//				dialog1.setTitle(Messages
//						.getString("SaturnWorkflowDialogInLogic.ChooseKeyValue")); //$NON-NLS-1$
//				Set<String> s = tempMap.keySet();
//				String ss[] = ConversionUtil.conversion(s);
//				for (int i = 0; i < ss.length; i++) {
//					ss[i] = ss[i].substring(ss[i].indexOf("::") + 2);
//				}
//				dialog1.setElements(ss);
//				dialog1.setMap(tempMap);
//
//				if (dialog1.open() == Window.OK) {
//
//					String expression = (String) dialog1.getFirstResult();
//					String expressions[] = expression.split("--");
//					expression = expressions[1].trim() + expressions[0].trim();
//					expressionText.setText(expression);
//
//					String key = saturnWorkflowNodeInLogic.findTheProject()
//							.getName()
//							+ "::" + expressionText.getText();
//					Document doc = tempMap.get(key);
//					if (doc != null) {
//						String strVersion = getInformationNodeValue(doc,
//								"version");
//						String strName = getInformationNodeValue(doc, "name");
//						String strDescription = getInformationNodeValue(doc,
//								"description");
//						versionText.setText(strVersion);
//						descriptionText.setText(strDescription);
//						nameText.setText(strName);
//						List<SaturnParameter> list = docmentForSaturnParameters(doc);
//						operateParameters(list);
//						tableViewer.setInput(tableVisualListTemp);
//					}
//				}
//				serach = false;
				
				OneCompontentSearchDialog searchDialog = new OneCompontentSearchDialog(
						shell,saturnWorkflowNodeInLogic);
				searchDialog.setTitle(Messages
						.getString("SaturnWorkflowDialogInLogic.ChooseKeyValue")); //$NON-NLS-1$
				
				if (searchDialog.open() == Window.OK) {
					SearchResult expression = (SearchResult)searchDialog.getFirstResult();
					expressionText.setText(expression.getKey());
				
					Document doc = expression.getDocument();
					if (doc != null) {
						String strVersion = getInformationNodeValue(doc,
								"version");
						String strName = getInformationNodeValue(doc, "name");
						String strDescription = getInformationNodeValue(doc,
								"description");
						versionText.setText(strVersion);
						descriptionText.setText(strDescription);
						nameText.setText(strName);
						List<SaturnParameter> list = docmentForSaturnParameters(doc);
						operateParameters(list);
						tableViewer.setInput(tableVisualListTemp);
					}
				}
			}
		});

		versionLabel = new Label(container, SWT.NONE);
		final GridData gd_versionLabel = new GridData();
		gd_versionLabel.verticalIndent = 10;
		versionLabel.setLayoutData(gd_versionLabel);
		versionLabel.setText(Messages
				.getString("SaturnWorkflowDialogInLogic.CopyRight")); //$NON-NLS-1$

		versionText = new Text(container, SWT.BORDER | SWT.READ_ONLY);
		final GridData gd_versionText = new GridData(SWT.FILL, SWT.FILL, true,
				false, 2, 1);
		gd_versionText.verticalIndent = 10;
		gd_versionText.horizontalIndent = 10;
		versionText.setLayoutData(gd_versionText);

		descriptionLabel = new Label(container, SWT.NONE);
		final GridData gd_descriptionLabel = new GridData(SWT.LEFT, SWT.TOP,
				false, false);
		gd_descriptionLabel.verticalIndent = 14;
		descriptionLabel.setLayoutData(gd_descriptionLabel);
		descriptionLabel.setText(Messages
				.getString("SaturnWorkflowDialogInLogic.description")); //$NON-NLS-1$

		descriptionText = new Text(container, SWT.V_SCROLL | SWT.BORDER
				| SWT.READ_ONLY);
		final GridData gd_descriptionText = new GridData(SWT.FILL, SWT.FILL,
				true, false, 2, 1);
		gd_descriptionText.heightHint = 53;
		gd_descriptionText.verticalIndent = 10;
		gd_descriptionText.horizontalIndent = 10;
		descriptionText.setLayoutData(gd_descriptionText);

		creatorLabel = new Label(container, SWT.NONE);
		final GridData gd_creatorLabel = new GridData();
		gd_creatorLabel.verticalIndent = 10;
		creatorLabel.setLayoutData(gd_creatorLabel);
		creatorLabel.setText(Messages
				.getString("SaturnWorkflowDialogInLogic.creater")); //$NON-NLS-1$

		creatorText = new Text(container, SWT.BORDER);
		creatorText.setTextLimit(50);
		final GridData gd_creatorText = new GridData(SWT.FILL, SWT.FILL, true,
				false, 2, 1);
		gd_creatorText.verticalIndent = 10;
		gd_creatorText.horizontalIndent = 10;
		creatorText.setLayoutData(gd_creatorText);

		transactionTypeLabel = new Label(container, SWT.WRAP);
		final GridData gd_transactionTypeLabel = new GridData(SWT.FILL,
				SWT.CENTER, true, false);
		gd_transactionTypeLabel.verticalIndent = 14;
		transactionTypeLabel.setLayoutData(gd_transactionTypeLabel);
		transactionTypeLabel.setText(Messages
				.getString("SaturnWorkflowDialogInLogic.BusinessType")); //$NON-NLS-1$

		transactionTypeCombo = new Combo(container, SWT.READ_ONLY);
		final GridData gd_transactionTypeCombo = new GridData(SWT.FILL,
				SWT.CENTER, true, false, 2, 1);
		gd_transactionTypeCombo.verticalIndent = 10;
		gd_transactionTypeCombo.horizontalIndent = 10;
		transactionTypeCombo.setLayoutData(gd_transactionTypeCombo);
		transactionTypeCombo
				.setItems(SelectionCandidate.transactionTypesForLogic);
		transactionTypeCombo.select(0);

		final Group group = new Group(container, SWT.NONE);
		group.setLayout(new FormLayout());
		group.setText(Messages.getString("SaturnWorkflowDialogInLogic.DesignParameter")); //$NON-NLS-1$

		final GridData gd_group = new GridData(SWT.FILL, SWT.FILL, true, true,
				3, 1);
		gd_group.heightHint = 161;
		gd_group.horizontalIndent = 3;
		gd_group.verticalIndent = 10;
		group.setLayoutData(gd_group);

		tableViewer = new TableViewer(group, SWT.BORDER | SWT.MULTI
				| SWT.FULL_SELECTION);
		table = tableViewer.getTable();
		final FormData fd_table = new FormData();
		fd_table.top = new FormAttachment(0, 6);
		fd_table.left = new FormAttachment(0, 10);
		fd_table.bottom = new FormAttachment(100, -9);
		fd_table.right = new FormAttachment(100, -10);
		table.setLayoutData(fd_table);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);

		tableViewer.setContentProvider(new TableViewerContentProvider());
		tableViewer.setLabelProvider(new TableViewerLableProvider());

		tableViewer.setColumnProperties(new String[] { "id", "valueKey",
				"name", "classType", "passingType", "scope", "description" });

		CellEditor[] cellEditor = new CellEditor[7];
		cellEditor[0] = null;
		cellEditor[1] = new TextCellEditor(tableViewer.getTable());
		cellEditor[2] = null;
		cellEditor[3] = null;
		cellEditor[4] = null;
		cellEditor[5] = null;
		cellEditor[6] = null;

		tableViewer.setCellEditors(cellEditor);
		tableViewer.setCellModifier(new MyCellModifierParameterFromWorkflow(
				tableViewer));

		final TableColumn IDColumn = new TableColumn(table, SWT.NONE);
		IDColumn.setWidth(67);
		IDColumn.setText(Messages.getString("SaturnWorkflowDialogInLogic.ParameterId")); //$NON-NLS-1$

		final TableColumn expressionColumn = new TableColumn(table, SWT.NONE);
		expressionColumn.setWidth(90);
		expressionColumn.setText(Messages
				.getString("SaturnWorkflowDialogInLogic.Expression")); //$NON-NLS-1$

		final TableColumn nameColumn = new TableColumn(table, SWT.NONE);
		nameColumn.setWidth(90);
		nameColumn.setText(Messages.getString("SaturnWorkflowDialogInLogic.ParaName")); //$NON-NLS-1$

		final TableColumn classTypeColumn = new TableColumn(table, SWT.NONE);
		classTypeColumn.setWidth(100);
		classTypeColumn.setText(Messages
				.getString("SaturnWorkflowDialogInLogic.ParaType")); //$NON-NLS-1$

		final TableColumn passingTypeColumn = new TableColumn(table, SWT.NONE);
		passingTypeColumn.setWidth(85);
		passingTypeColumn.setText(Messages
				.getString("SaturnWorkflowDialogInLogic.InputOutput")); //$NON-NLS-1$

		final TableColumn scopeColumn = new TableColumn(table, SWT.NONE);
		scopeColumn.setWidth(75);
		scopeColumn
				.setText(Messages.getString("SaturnWorkflowDialogInLogic.DataDomain")); //$NON-NLS-1$

		final TableColumn descriptionColumn = new TableColumn(table, SWT.NONE);
		descriptionColumn.setWidth(170);
		descriptionColumn.setText(Messages
				.getString("SaturnWorkflowDialogInLogic.ParaDesription")); //$NON-NLS-1$

		/**
		 * 初始化操作
		 * 
		 */
		idText.setText(saturnWorkflowNodeInLogic.getId().trim());
		nameText.setText(saturnWorkflowNodeInLogic.getName().trim());
		nameText.setSelection(saturnWorkflowNodeInLogic.getName().trim().length());
		descriptionText.setText(saturnWorkflowNodeInLogic.getDescription()
				.trim());
		versionText.setText(saturnWorkflowNodeInLogic.getVersion().trim());
		expressionText.setText(saturnWorkflowNodeInLogic.getKey().trim());
		creatorText.setText(saturnWorkflowNodeInLogic.getCreator().trim());
		transactionTypeCombo.setText(saturnWorkflowNodeInLogic
				.getTransactionType().trim());
		tableViewer.setInput(ConversionUtil
				.scopeMapFromXmlToSurface(tableVisualListTemp));

		return area;
	}

	@Override
	protected void buttonPressed(int buttonId) {
		if (parameterlist == null) {
			return;
		}
		if (buttonId == IDialogConstants.OK_ID) {
			saturnWorkflowNodeInLogic.setDescription(descriptionText.getText()
					.trim());
			saturnWorkflowNodeInLogic.setKey(expressionText.getText().trim());
			saturnWorkflowNodeInLogic.setTransactionType(transactionTypeCombo
					.getText().trim());
			saturnWorkflowNodeInLogic.setVersion(versionText.getText().trim());
			saturnWorkflowNodeInLogic.setCreator(creatorText.getText().trim());
			parameterlist.get(parameterlist.size() - 1).setValueKey(
					creatorText.getText().trim());
			this.parameterlist = copyTableViewerListToParameterList(parameterlist);
			ConversionUtil.scopeMap(parameterlist);
			saturnWorkflowNodeInLogic.setParameters(parameterlist); // 问题出现在这里
			saturnWorkflowNodeInLogic.setName(nameText.getText().trim());
		}
		super.buttonPressed(buttonId);
	}

	@Override
	protected Point getInitialSize() {
		return new Point(640, 540);
	}

	protected int getShellStyle() {
		return SWT.CLOSE | SWT.RESIZE;
	}

	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setImage(Activator.getImage(Images.SATURN_ICONS_SMALLNAME));
	}

	private List<SaturnParameter> docmentForSaturnParameters(Document document) {
		List<SaturnParameter> parameterList = new ArrayList<SaturnParameter>();
		NodeList list1 = document.getDocumentElement().getElementsByTagName(
				"activity");
		Node startActivety = getStartActivety(list1);
		if (startActivety != null) {
			List<Node> formDataList = this.getFormData(startActivety);
			for (Node n : formDataList) {
				String formDataKey = SaturnW3CUtil.getNodeAttributeValue(n,
						"key");
				String formDataName = SaturnW3CUtil.getNodeAttributeValue(n,
						"name");
				String formDataID = SaturnW3CUtil.getNodeAttributeValue(n, "id");
				SaturnParameter parameter = new SaturnParameter();
				parameter.setDescription(formDataName);
				parameter.setId(formDataID);
				parameter.setName(formDataKey);
				parameter.setValueKey(formDataKey);
				parameter.setClassType("java.lang.String");
				parameter.setPassingType("in");
				parameter.setScope("logic");
				parameterList.add(parameter);
			}

		}
		return parameterList;
	}

	private List<Node> getFormData(Node node) {
		List<Node> formDataList = new ArrayList<Node>();
		NodeList list = node.getChildNodes();
		for (int i = 0; i < list.getLength(); i++) {
			if (list.item(i).getNodeName().equals("formData")) {
				NodeList dataList = list.item(i).getChildNodes();
				for (int j = 0; j < dataList.getLength(); j++) {
					if ("data".equals(dataList.item(j).getNodeName())) {
						formDataList.add(dataList.item(j));
					}
				}
			}
		}
		System.out.println(formDataList.size());
		return formDataList;
	}

	private Node getStartActivety(NodeList nodelist) {
		for (int i = 0; i < nodelist.getLength(); i++) {
			if ("start".equals(SaturnW3CUtil.getNodeAttributeValue(nodelist
					.item(i), "type"))) {
				return nodelist.item(i);
			}
		}
		return null;
	}

	protected void setParameterList(List<SaturnParameter> parameterlist) {
		List<SaturnParameter> showParameterlist = new ArrayList<SaturnParameter>();

		for (SaturnParameter parameter : parameterlist) {
			showParameterlist.add(new SaturnParameter(parameter));
		}

		this.parameterlist = showParameterlist;

		operateParameters(this.parameterlist);
	}

	private void operateParameters(List<SaturnParameter> parameterlist) {
		SaturnParameter saturnParameter = new SaturnParameter();
		saturnParameter.setId(String.valueOf(parameterlist.size() + 1));
		saturnParameter.setName("creator");
		saturnParameter.setValueKey("");
		saturnParameter.setClassType("java.lang.String");
		saturnParameter.setPassingType(SelectionCandidate.passingTypes[0]);
		saturnParameter.setScope("logic");

		if (parameterlist.size() == 0) {
			parameterlist.add(saturnParameter);
		} else if (!"creator".equals(parameterlist
				.get(parameterlist.size() - 1).getName().trim())) {
			parameterlist.add(saturnParameter);
			this.parameterlist = parameterlist;
		} else {
			this.parameterlist = parameterlist;
		}

		getTableVisual(this.parameterlist);
		saturnWorkflowNodeInLogic.setCreator(parameterlist.get(
				parameterlist.size() - 1).getValueKey().trim());
	}

	private void getTableVisual(List<SaturnParameter> parameterlist) {
		List<SaturnParameter> tableVisualList = new ArrayList<SaturnParameter>();
		for (SaturnParameter tp : parameterlist) {
			SaturnParameter tpr = new SaturnParameter((SaturnParameter) tp);
			tableVisualList.add(tpr);
		}

		tableVisualList.remove(tableVisualList.size() - 1);
		this.tableVisualListTemp = tableVisualList;
	}

	private List<SaturnParameter> copyTableViewerListToParameterList(
			List<SaturnParameter> parameterlist) {

		tableVisualListTemp.add(parameterlist.get(parameterlist.size() - 1));

		parameterlist = tableVisualListTemp;

		return parameterlist;
	}

	private String getInformationNodeValue(Document doc, String childNodeName) {
		NodeList nodeList = doc.getDocumentElement().getElementsByTagName(
				"information");
		Node informationNode = nodeList.item(0);
		return SaturnW3CUtil.getChildNodeValue(informationNode, childNodeName);
	}

	class GUIUpdater implements Runnable {
		private IProgressMonitor monitor;

		GUIUpdater(IProgressMonitor monitor) {
			this.monitor = monitor;
		}

		public void run() {
			for (int i = 0; i < 34; i++) {
				try {
					Thread.sleep(800);
					this.monitor.worked(5);
					if (serach == true) {
						this.monitor.worked(100);
						break;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	
	
}